public class HashBuck {
    static class Node{
        public int val;
        public int key;
        public Node next;
        public Node(int key,int val){
            this.key = key;
            this.val = val;
        }
    }
    public Node[] array;
    public int usedSize;
    public static final double DEFAULT_LOAD_FACTOR = 0.75;
    public HashBuck(){
        this.array = new Node[8];
    }
    //存放元素
    public void put(int key,int val){
        int index = key%array.length;
        //遍历index的下标
        //1.查看是否有key,有一样的替换val值
        //2.没有的话 进行头插法
        Node cur = array[index];
        while(cur!=null){
            if(cur.key==key){
                cur.val = val;
                return ;
            }
            cur = cur.next;
        }
        //没有相同的元素，开始插入
        Node node = new Node(key,val);
        node.next = array[index];
        array[index] = node;
        usedSize++;
        //检查 当前哈希表中是否超过了负载因子
        if(loadFactor()>=DEFAULT_LOAD_FACTOR){
            //扩容
            resize();
        }

    }
    //扩容
    //注意：需要注意遍历每个链表的节点，重新哈希到新的哈希表
    private void resize(){
        Node[] temp = new Node[2*array.length];
        for(int i = 0;i<array.length;i++){
            Node cur = array[i];
            while(cur!=null){
                Node curNext = cur.next;
                int index = cur.key%temp.length;
                cur.next = temp[index];
                temp[index] = cur;
                cur = curNext;
            }
        }
        array = temp;

    }
    //检查 当前哈希表中是否超过了负载因子
    private double loadFactor(){
        return usedSize*1.0/array.length;
    }
    //通过key的值，获取val的值
    public int get(int key){
        int index = key%array.length;
        Node cur = array[index];
        while(cur!=null){
            if(cur.key==key){
                return cur.val;
            }else{
                cur = cur.next;
            }
        }
        return -1;

    }
}
